<template>
  <div class="art-full-height">
    <!-- 搜索栏 -->
    <ArtSearchBar
      v-model="searchForm"
      :items="formItems"
      :show-expand="true"
      @search="handleSearch"
      @reset="resetSearchParams"
    />

    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader
        v-model:columns="columnChecks"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      >
        <template #left>
          <ElSpace wrap>
            <ElButton type="primary"  @click="handleAdd"> 新增类型 </ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 数据表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        :show-overflow-tooltip="true"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <!-- 报事类型列 -->
        <template #issueTypeName="{ row }">
          <DictTag
            :dict-type="'10200'"
            :value="row.issueTypeName"
            :fallback-text="getRecordTypeText(row.issueTypeName)"
            :auto-tag-type="true"
          />
        </template>

        <!-- 操作列 -->
        <template #operation="{ row }">
          <div class="flex items-center gap-2">
            <ArtButtonTable type="view" @click="handleView(row)"> 查看 </ArtButtonTable>
            <ArtButtonTable type="edit" @click="handleEdit(row)"> 编辑 </ArtButtonTable>
            <ArtButtonTable type="delete" @click="handleDelete(row)"> 删除 </ArtButtonTable>
          </div>
        </template>
      </ArtTable>


      <!-- 新增/编辑对话框 -->
      <RestEditDialog
        v-model="editDialogVisible"
        :rest-data="currentRestData"
        ref="dialogRef"
        @refresh="loadTableData"
        @success="handleDialogSuccess"
      />
    </ElCard>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, h } from 'vue'
import { dayjs, ElMessage, ElMessageBox,  ElInput, ElButton, ElSpace,  } from 'element-plus'
import { useTable } from '@/composables/useTable'
import ArtSearchBar from '@/components/core/forms/art-search-bar/index.vue'
import ArtTable from '@/components/core/tables/art-table/index.vue'
import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
import { DictTag, DictSelect } from '@/components/core/dics/index.vue'
import RestEditDialog from './modules/edit-dialog.vue'
// @ts-ignore
import {
  recordIssueTypeListDataUsingPost,
  recordIssueTypeDeleteDataUsingPost,
  apiDictListByTypeUsingPost
} from '@/api'

// 类型定义
interface SearchForm {
  recordType: number | null
  issueUpFlag: number | null
}

const dialogRef = ref(null)
// 响应式数据
const searchForm = ref<SearchForm>({
  recordType: null,
  issueUpFlag: null,
})



// 搜索表单配置
const formItems = computed(() => {
  // 确保能获取到最新的 searchForm 值
  const currentForm = searchForm.value
  
  return [
    {
      key: 'issueTypeName',
      label: '报事类型',
      type: () => h(ElInput, {
        placeholder: '请输入报事类型',
        clearable: true,
        modelValue: currentForm.issueTypeName,
        'onUpdate:modelValue': (value: any) => {
          searchForm.value.issueTypeName = value
        },
        // 添加 onClear 事件处理，点击清空按钮时置空表单值
        onClear: () => {
          searchForm.value.issueTypeName = null
        }
      })
    },
    {
      key: 'issueUpFlag',
      label: '上架状态',
      type: () => h(DictSelect, {
        dictType: '1',
        placeholder: '请选择上架状态',
        clearable: true,
        modelValue: currentForm.issueUpFlag,
        'onUpdate:modelValue': (value: any) => {
          searchForm.value.issueUpFlag = value
        },
        // 添加 onClear 事件处理，点击清空按钮时置空表单值
        onClear: () => {
          searchForm.value.issueUpFlag = null
        }
      })
    },
]
})

const editDialogVisible = ref(false)
const currentRestData = ref<GeoRestVo | null>(null)

const handleDialogSuccess = () => {
    editDialogVisible.value = false
    currentRestData.value = null
    getData()
  }

// 使用 useTable 管理表格数据
const {
  columns,
  columnChecks,
  data,
  loading,
  pagination,
  getData,
  searchParams,
  handleSizeChange,
  handleCurrentChange,
  refreshData
} = useTable({
  core: {
    apiFn: recordIssueTypeListDataUsingPost,
    apiParams: {
      body: {
        current: 1,
        size: 10,
      }
    },
    paginationWrapper: 'body', // 将分页参数包装到 body 对象中
    columnsFactory: () => [
      {
        prop: 'issueTypeName',
        label: '报事类型',
        align: 'center',
      },
      {
        prop: 'issueScoreNum',
        label: '奖励积分',
        align: 'center',
      },
      {
        prop: 'issueUpFlag',
        label: '是否上架',
        align: 'center',
        formatter(row) {
    return getIssueUpLabel(row.issueUpFlag);
  },
      },
      
      {
        prop: 'operation',
        label: '操作',
        fixed: 'right',
        align: 'center',
        width:180,
        headerAlign: 'center',
        useSlot: true
      }
    ]
  }
})

const showSearchBar = ref(false)

const IssueUpType = ref([])

// 页面加载时自动获取数据
onMounted(() => {
  getData()
  getDictType()
})

const handleSearch = () => {
  searchParams.body.issueTypeName = searchForm.value.issueTypeName || undefined
  getData()
}
const resetSearchParams = () => {
  
  // 重置搜索参数
  searchParams.body.issueTypeName = undefined
  
  // 重置表单数据 - 逐个设置确保响应式更新
  searchForm.value.issueTypeName = null
  
  // 重新获取数据
  getData()
}

const handleAdd = () => {
  currentRestData.value = null
    editDialogVisible.value = true
}



// 查看报事详情
const handleView = async (row) => {
    // 重置详情数据
    currentRestData.value = null
    // 打开弹框
    if(dialogRef.value) {
      dialogRef.value.openDialog(row)
    }
}
// 编辑报事类型
const handleEdit = async (row) => {
    // 重置详情数据
    currentRestData.value = null
    // 打开弹框
    if(dialogRef.value) {
      dialogRef.value.openDialog(row)
    }
}

// 删除报事类型
const handleDelete = async (row) => {
  try {
      await ElMessageBox.confirm(`确定要删除报事类型"${row.issueTypeName}"吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      // 这里应该调用删除接口，暂时用提示代替
      await recordIssueTypeDeleteDataUsingPost({
          body: {
            id: row.id
          }
        })
      ElMessage.success('删除成功')
      getData()
    } catch {
      // 用户取消删除
    }
}

const getDictType = async() => {
    const res = await apiDictListByTypeUsingPost({body:[1]})
    IssueUpType.value = res[0].dictDataList
  }


const getIssueUpLabel = (value) => {
if(value){
  const matched = IssueUpType.value.find(item => item.dictValue === Number(value));
  return matched ? matched.dictLabel : '未知';
  }
}



const loadTableData = async () => {
  getData();
};
</script>

<style lang="scss" scoped>
.attachment-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  max-width: 200px;
}

.attachment-item {
  display: flex;
  align-items: center;
}

.image-preview {
  .attachment-image {
    width: 50px;
    height: 50px;
    border-radius: 4px;
    cursor: pointer;
    border: 1px solid #e4e7ed;
    transition: all 0.3s;
    object-fit: cover;
    
    &:hover {
      border-color: #409eff;
      transform: scale(1.05);
    }
  }
}

.file-link {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 2px 0;
  
  .el-link {
    font-size: 11px;
    white-space: nowrap;
  }
}

.text-gray-400 {
  color: #9ca3af;
  font-size: 12px;
}

.detail-container {
  .detail-item {
    margin-bottom: 16px;
    
    label {
      font-weight: 600;
      color: #606266;
      margin-right: 8px;
      display: inline-block;
      min-width: 80px;
    }
    
    span {
      color: #303133;
    }
    
    .detail-content {
      margin-top: 4px;
      padding: 8px 12px;
      background-color: #f5f7fa;
      border-radius: 4px;
      color: #303133;
      line-height: 1.5;
      white-space: pre-wrap;
      word-break: break-word;
    }
  }
}

.loading-container {
  padding: 20px;
}
</style>